<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, height=device-height">
    <title>狼吃羊</title>
    <link rel="stylesheet" type="text/css" href="css/withnet.css">
    <script type="text/javascript">
        var cssEl = document.createElement('style');
        document.documentElement.firstElementChild.appendChild(cssEl);
        function setPxPerRem(){
            var dpr = 1;
            //把viewport分成10份的rem，html标签的font-size设置为1rem的大小;
            var pxPerRem = document.documentElement.clientWidth * dpr / 10;
            cssEl.innerHTML = 'html{font-size:' + pxPerRem + 'px!important;}';
        }
        setPxPerRem();
    </script>
    <script type="text/javascript" src="boardnet.js"></script>
    <script type="text/javascript" src="position.js"></script>
    <script src="socket.io.js"></script>

</head>
<body>

<div style="text-align:center;white-space:nowrap">
    <div id="container"></div>
    <div id="sheepText" style="position: absolute; top: 49px; left: 20px;font-size:25px; color: sienna" align="left">欢迎来到狼吃羊 </div>
    <div id="list" style="height:300px;width:250px;overflow:auto">
        <table id="tableID">
            <tr>
                <th>房间名</th>
                <th>游戏状态</th>
            </tr>
            <tr>
                <td>点击对应房间名 </td>
                <td>游戏中</td>
            </tr>
            <tr>
                <td>进入游戏</td>
                <td>游戏中</td>
            </tr>
            <tr>
                <td>33</td>
                <td>游戏中</td>
            </tr>
            <tr>
                <td>222</td>
                <td>游戏中</td>
            </tr>

        </table>
    </div>

</div>
<div id="new">创建房间</div>
<div id="join">加入房间</div>

<!--<div id="leave">离开房间</div>-->
<div id="onemore">再来一局</div>
<div id="changerole">改为狼方</div>

<div id="chat"></div>
<div id="footer">
    <input id="text" type="text" placeholder="说点什么吧...">
    <span id="btn">发送</span>
</div>


<script>
    "use strict";
    var board = new Board(container, sheepText,"images/");	// 创建棋盘
    var sheeps=23
    var lesshheeps=12
    var me=0;
    var him;
    var start=false

    var socket = io.connect('http://39.108.85.104:3000');




    socket.on('rooms', function (data) {
        var rooms=data.rooms
        deleteTable();
        for ( var key in rooms) {
      //通过遍历对象属性的方法，遍历键值对，获得key，然后通过 对象[key]获得对应的值
            var name = key;
            var value = rooms[key];
            addRow(name,value)
        }

    });
    window.role=0
    function startGameA(m,h,r) {
        //startGame.innerText="重新开始"
        if(start){
            board.endGame()
        }
        me=m;
        him=h;
        board.startGame(sheeps,lesshheeps,me,him,r)
        start=true
        document.getElementById("new").style.display="none";
        document.getElementById("join").style.display="none";
//        document.getElementById("leave").style.display="block";
        document.getElementById("onemore").style.display="block";
        document.getElementById("changerole").style.display="block";
        document.getElementById("list").style.display="none";
        document.getElementById("footer").style.display="block";
        if(r==0){
            document.getElementById("changerole").innerText="改为羊方"
        }else{
            document.getElementById("changerole").innerText="改为狼方"
        }

        var btn = document.getElementById('btn');
        var text = document.getElementById('text');

        var chat = document.getElementById('chat')
        var time1;
        var time2;
        btn.onclick = function(){
            if(text.value ==''){
                alert('不能发送空消息');
            }else {
                chat.innerText="我："+text.value;
                me.emit('sendMessage',{ user_id : him,message:text.value})
                text.value=""
                clearTimeout(time2)
                time1=setTimeout("clearChat()", 10000)
            }
        }
        me.on('getMessage', function (data) {
            m=data.message;
            chat.innerText="对方："+m;
            clearTimeout(time1)
            time2=setTimeout("clearChat()", 10000)
        });
    }
    function clearChat() {
        var chat = document.getElementById('chat')
        chat.innerText="";
    }
    function newRoom()
    {
        var s=prompt("请输入房间名:","");//将输入的内容赋给变量 name ，
        //这里需要注意的是，prompt有两个参数，前面是提示的话，后面是当对话框出来后，

        if(s)//如果返回的有内容
        {
            if(s.length>8){
                alert("长度太长了，请重新建房")
                return
            }
            var partner=""
            socket.on('getPartner', function (data) {
                partner=data.user_id;
                socket.emit('giveHisId',{ user_id : partner})
                window.role=0
                startGameA(socket,partner,0);
                oneMore()
                changeRole()
                leave()
            });
            socket.emit('newRoom',{ user_id : s})

            socket.on('newRoomSuccess', function () {
                document.getElementById("list").style.display="none";
                document.getElementById("sheepText").innerText="请等待他人进入房间"
                alert("创建房间成功，快把房间名告诉你的小伙伴吧！")
            });

            socket.on('newRoomFailed', function () {
                alert("创建房间失败，房间名已存在")
            });

        }
    }
    function joinRoom()
    {
        var s=prompt("请输入房间名:","");//将输入的内容赋给变量 name ，
        //这里需要注意的是，prompt有两个参数，前面是提示的话，后面是当对话框出来后，

        if(s)//如果返回的有内容
        {
            socket.on('getOwnid', function (data) {
                window.role=1
                startGameA(socket,s,1)
                oneMore()
                changeRole()
                leave();
            });

            socket.on('joinRoomFailed', function () {
                alert("加入房间失败，房间名不存在")
            });
            socket.emit('joinRoom',{ user_id : s})
        }
    }
    document.getElementById("new").onclick = function () {
        newRoom()
    };
    document.getElementById("join").onclick = function () {
        joinRoom()
    };

    document.getElementById("onemore").onclick = function () {
        me.emit("onemore",{user_id : him})
        alert("请等待对方确认！");
    };

    document.getElementById("changerole").onclick = function () {
        me.emit("changeRole",{user_id : him})
        alert("请等待对方确认！");
    };
    function leave() {
        if(me!=0){
            me.on('leave', function () {
                alert("对方已离开房间！请刷新，重新建房。")
            });
        }
    }
    function oneMore() {
        if(me!=0){
            me.on('agreeOneMore', function () {
                if(confirm("对方请求再来一局，是否同意")) {
                    me.emit('agree',{  user_id : him})
                    startGameA(me,him, window.role);
                } else {
                    me.emit('disagree',{ user_id : him})
                }

            });
            me.on('agree', function () {
                startGameA(me,him, window.role)
            });
            me.on('disagree', function () {
                alert("对方不同意继续！")
            });
        }

    }

    function changeRole() {
        if(me!=0){
            me.on('agreeChangeRole', function () {
                if(confirm("对方请求刚换角色重开游戏，是否同意")) {
                    me.emit('agreeRole',{  user_id : him})
                    if(window.role==0){
                        window.role=1
                    }else{
                        window.role=0
                    }
                    startGameA(me,him, window.role);
                } else {
                    me.emit('disagreeRole',{ user_id : him})
                }

            });
            me.on('agreeRole', function () {
                if(window.role==0){
                    window.role=1
                }else{
                    window.role=0
                }
                startGameA(me,him, window.role)
            });
            me.on('disagreeRole', function () {
                alert("对方不同意刚换角色！")
            });
        }

    }
    function deleteTable() {
        var t=document.getElementById('tableID')
        var currentRows = t.rows.length;
        while(currentRows>5){
            t.deleteRow(currentRows-1)
            currentRows = t.rows.length;
        }

    }
    function addRow(name,status) {
        //原来的行数    比如：此处获得表格的行数是5，则每一行对应的index是0~4，所以下面在insertRow时，使用的是表格的当前行数
        var currentRows = document.getElementById("tableID").rows.length;
        var insertTr = document.getElementById("tableID").insertRow(currentRows);
        var insertTd = insertTr.insertCell(0);
        insertTd.innerHTML = name;


        insertTd = insertTr.insertCell(1);
        if(status==0){
            insertTd.innerHTML = "等待中";
            table.rows[currentRows].cells[0].onclick = function () {
                tableText(this);
            };
        }else{
            insertTd.innerHTML = "游戏中";
        }


    }
    var table = document.getElementById("tableID");
//    if (table != null) {
//        for (var i = 0; i < table.rows.length; i++) {
//         //   for (var j = 0; j < table.rows[i].cells.length; j++)
//                table.rows[i].cells[0].onclick = function () {
//                    tableText(this);
//                };
//        }
//    }

    function tableText(tableCell) {
        var s = tableCell.innerHTML
        if (confirm("确定加入房间 " + s + " 吗？")) {
            socket.on('getOwnid', function (data) {
                window.role = 1
                startGameA(socket, s, 1)
                oneMore()
                changeRole()
                leave();
            });

            socket.on('joinRoomFailed', function () {
                alert("加入房间失败，房间名不存在")
            });
            socket.emit('joinRoom', {user_id: s})
        }
    }
</script>
</body>
</html>